package sunwin.yois.web.controller;

import jodd.datetime.JDateTime;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import sunwin.yois.web.common.R;
import sunwin.yois.web.common.YoisAjaxAnswer;
import sunwin.yois.web.common.YoisControllerDefaultData;
import sunwin.yois.web.common.resolverArg.YoisArrayParam;
import sunwin.yois.web.common.resolverArg.YoisDateParam;
import sunwin.yois.web.common.resolverArg.YoisTimeParam;
import sunwin.yoms.comm.YomsException;
import sunwin.yoms.comm.YomsHelper;
import sunwin.yoms.comm.model.NameAndValueModel;
import sunwin.yoms.comm.model.TimeSpan;
import sunwin.yoms.service.comm.exception.SubscribeErrorException;
import sunwin.yoms.service.comm.exception.SubscribeOccupiedException;
import sunwin.yoms.service.resource.SubscribeOrderService;

import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by mt on 2015-8-31.
 */
@Controller
public class SubscriptionController {
    @Autowired
    private SubscribeOrderService subscribeOrderService;
    @Autowired
    private YoisControllerDefaultData defaultData;
    @Autowired
    private YomsHelper yomsHelper;

    /**
     * 根据场馆ID获取预约时间
     *
     * @param sid
     * @return
     */
    @RequestMapping(value = R.GetDateBySid, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object getSubscribeDateByUidWithSid(int sid) {
        YoisAjaxAnswer answer = new YoisAjaxAnswer();
        answer.setSuccess(true);

        int uid = defaultData.getCurrentYimsUserDetails().getUserid();

        try {
            List<JDateTime> dateTimes = subscribeOrderService.getSubscribeDateByUidWithSid(uid, sid);
            List<String> dateStrings = new ArrayList<>();
            for (JDateTime date : dateTimes) {
                dateStrings.add(date.toString("YYYY-MM-DD"));
            }

            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(dateStrings);

            answer.setData(jsonArray.toString());
        } catch (YomsException e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }

        JSONObject jsonObject = JSONObject.fromObject(answer);

        return jsonObject.toString();
    }

    /**
     * 根据用户ID，场馆ID，预约日期获取时间段
     *
     * @param sid
     * @param date
     * @return
     */
    @RequestMapping(value = R.GetTimesByDateWithSid, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object getSubscribeDateTimeSpanByUidWithSidWithDate(int sid, @YoisDateParam JDateTime date) {
        YoisAjaxAnswer answer = new YoisAjaxAnswer();
        answer.setSuccess(true);

        int uid = defaultData.getCurrentYimsUserDetails().getUserid();

        try {
            List<TimeSpan> timeSpans = subscribeOrderService.getSubscribeDateTimeSpanByUidWithSidWithDate(uid, sid, date);
            List<NameAndValueModel> nameAndValueModels = new ArrayList<>();
            for (TimeSpan timeSpan : timeSpans) {
                NameAndValueModel navm = new NameAndValueModel();
                navm.setName(timeSpan.getStartTimeString());
                navm.setValue(timeSpan.getEndTimeString());

                nameAndValueModels.add(navm);
            }

            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(nameAndValueModels);

            answer.setData(jsonArray.toString());
        } catch (YomsException e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }

        JSONObject jsonObject = JSONObject.fromObject(answer);

        return jsonObject.toString();
    }

    @RequestMapping(value = R.CancelSubscribe, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object cancelSubscribeOrder(int sid, @YoisDateParam JDateTime dateTime) {
        YoisAjaxAnswer answer = new YoisAjaxAnswer();
        answer.setSuccess(true);

        int uid = defaultData.getCurrentYimsUserDetails().getUserid();

        try {
            subscribeOrderService.cancelSubscribe(uid, sid, dateTime);
        } catch (Exception e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }

        JSONObject jsonObject = JSONObject.fromObject(answer);

        return jsonObject.toString();
    }

    /**
     * 订阅场馆
     *
     * @param startDate 起始日期
     * @param endDate   截至日期
     * @param times     预约时间段
     * @param sType     预约类型
     * @param sid       预约场馆
     * @param isRandom  时间段是否随系统定义
     * @return
     * @throws Exception
     */
    @RequestMapping(value = R.SubscribeStadium, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object subscribeStadium(
            @YoisDateParam JDateTime startDate,
            @YoisDateParam JDateTime endDate,
            @YoisArrayParam List<String> times,
            int sType,    //0.普通预约；1.周期天预约；2.周期星期预约；3.周期月预约
            int sid,
            boolean isRandom) throws Exception {
        YoisAjaxAnswer answer = new YoisAjaxAnswer();
        answer.setSuccess(true);

        int uid = defaultData.getCurrentYimsUserDetails().getUserid();

        try {
            switch (sType) {
                case 0:
                    subscribeOrderService.oneDayOfSubscribe1(sid, uid, null, startDate, subscribeOrderService.convertStringToTimespan(times), isRandom);
                    break;
                case 1:
                    subscribeOrderService.everyDayOfSubscribe(sid, uid, startDate, endDate, subscribeOrderService.convertStringToTimespan(times), isRandom);
                    break;
                case 2:
                    subscribeOrderService.everyWeekOfSubscribe(sid, uid, startDate, endDate, subscribeOrderService.convertStringToTimespan(times), isRandom);
                    break;
                case 3:
                    subscribeOrderService.everyMonthOfSubscribe(sid, uid, startDate, endDate, subscribeOrderService.convertStringToTimespan(times), isRandom);
                    break;
                default:
                    throw new YomsException("无法解析预约类型");
            }
        } catch (SubscribeOccupiedException e) {
            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(e.getOccupiedTimeSpans());

            answer.setDataType("timeSpans");
            answer.setSuccess(false);
            answer.setException(e.getMessage());
            answer.setData(jsonArray.toString());
        } catch (SubscribeErrorException e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }

        JSONObject json = JSONObject.fromObject(answer);
        return json.toString();
    }


    /**
     * 根据日期获取当天有效的时间段
     *
     * @param date
     * @return
     */
    @RequestMapping(value = R.GetTimesByDate, method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object getTimesByDate(int sid, @YoisDateParam JDateTime date) {
        List<TimeSpan> timeSpans = null;
        JSONArray jsonArray = new JSONArray();
        List<NameAndValueModel> nameAndValueModels = new ArrayList<>();

        try {
            timeSpans = subscribeOrderService.getStadiumBusinessHours(sid, date);

            for (TimeSpan timeSpan : timeSpans) {
                String value = String.format("%s-%s", timeSpan.getStartTimeString(), timeSpan.getEndTimeString());

                NameAndValueModel nameAndValueModel = new NameAndValueModel();
                nameAndValueModel.setValue(value);
                nameAndValueModels.add(nameAndValueModel);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        jsonArray.addAll(nameAndValueModels);

        return jsonArray.toString();
    }

    /**
     * 批量取消预约
     */
    @RequestMapping(value = R.CancelSubscribeBatch, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    public Object CancelSubBatch(int sid,
                                 @YoisDateParam JDateTime startDate,
                                 @YoisDateParam JDateTime endDate) throws YomsException {
        YoisAjaxAnswer answer = new YoisAjaxAnswer();
        answer.setSuccess(true);
        int uid = defaultData.getCurrentYimsUserDetails().getUserid();
        try {
            subscribeOrderService.batchCancelSubscribe(uid, sid, startDate, endDate);
        } catch (Exception e) {
            answer.setSuccess(false);
            answer.setException(e.getMessage());
        }
        JSONObject jsonObject = JSONObject.fromObject(answer);
        return jsonObject.toString();
    }

    /**
     * 按时间段取消预约
     */
    @RequestMapping(value = R.CancelSubscribeTime, method = RequestMethod.POST)
    @ResponseBody
    public Object CancelSubByTime(int sid, @YoisDateParam JDateTime date,
                                  @YoisTimeParam Time startTime,
                                  @YoisTimeParam Time endTime) throws YomsException {
        YoisAjaxAnswer answer = new YoisAjaxAnswer();
        answer.setSuccess(true);
        Date date1 = date == null ? null : date.convertToDate();
        Time time1 = startTime == null ? null : startTime;
        Time time2 = endTime == null ? null : endTime;
        TimeSpan timeSpan = new TimeSpan();
        timeSpan.setStartTime(time1);
        timeSpan.setEndTime(time2);
        List<TimeSpan> timeSpans = new ArrayList<>();
        timeSpans.add(timeSpan);
        long timeSpanLong = subscribeOrderService.convertTimeSpansToLong(timeSpans);
        try {
            subscribeOrderService.cancelSubscribe(sid, date1, timeSpanLong);
        } catch (Exception e) {
            String message = e.getMessage();
            answer.setSuccess(false);
            answer.setException(message);
        }
        JSONObject jsonObject = JSONObject.fromObject(answer);
        return jsonObject.toString();
    }
}
